import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Table, Button, Row, Col, Layout, Breadcrumb, Menu, Dropdown, Popconfirm, Icon, Input, Modal, Form } from 'antd';
import style from '../../../styles/TableCss.less';
import { Link } from 'dva/router';
// import reqwest from 'reqwest';
import { reqwest_get, reqwest_post } from '../../../utils/Reqwest.js';
// import request from '../../../utils/request.js'
const { Content } = Layout;
const FormItem = Form.Item;
class StoresList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      formLoading: false,
      selectId: null,
      data: [],
      dropDown: '所有渠道门店',
      columns: [{
        title: '所属渠道',
        dataIndex: 'regions',
      }, {
        title: 'ID',
        dataIndex: 'id',
      }, {
        title: '门店名称',
        dataIndex: 'name',
        width: '20%',
      }, {
        title: '运营专员',
        dataIndex: 'user_name',
      }, {
        title: '手机号',
        dataIndex: 'user_mobile',
      }, {
        title: '提成(%)',
        dataIndex: 'rate',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Button type="primary" onClick={() => this.showModal(record.id)}>编辑</Button>
          </span>
        ),
      }],
    };
  }
  // onDelete(key,e,_this){
  //   const data = _this.state.data.filter(item => item.key !== key);
  //   // _this.setState({data });
  //   reqwest({
  //     url: window.host+'/api/clues/'+key,
  //     method: 'delete',
  //     crossOrigin: true,
  //     data: {
  //       access_token:localStorage['token'],
  //     },
  //     type: 'json',
  //   }).then((data) => {
  //     console.log(data);
  //     const pagination = { ...this.state.pagination };
  //     _this.fetch()
  //   });
  // }
  handleTableChange = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    // console.log(pagination.current)
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    });
    this.fetch({
      results: pagination.pageSize,
      page: pagination.current,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  }
  showModal = (id) => {
    this.setState({ selectId: id, visible: true });
  }
  handleSubmit = (e) => {
    let _this = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // _this.setState({ selectId: null });
        console.log('Received values of form: ', values);
        reqwest_post('/api/stores/' + _this.state.selectId, {
          access_token: localStorage['token'],
          store: { rate: values.rate },
        }, (data) => {
          if (data.status === 'success') {
            _this.fetch({ page: 1 });
            _this.setState({ selectId: null, visible: false });
          }
        });
      }
    });
  }
  handleCancel = () => {
    this.setState({ visible: false });
  }
  fetch = (params = {}) => {
    console.log('params:', params);
    let _data = [];
    let _this = this;
    this.setState({ loading: true });
    reqwest_get('/api/regions/' + _this.props.location.query.uid + '/stores', {
      access_token: localStorage['token'],
      page: params.page,
      pre: 10,
    }, (data) => {
      if (data.status === 'success') {
        const pagination = { ...this.state.pagination };
        // sessionStorage['regions']=JSON.stringify(data.regions);
        pagination.total = data.total;
        for (let i of data.list) {
          _data.push({
            key: i.id,
            id: i.id,
            regions: i.region_name,
            name: i.name,
            user_name: i.user_name,
            user_mobile: i.user_mobile,
            rate: i.rate,
            // contact:i.contact,
            // store:i.name,
            // region_id:i.region_id,
            // address:i.address,
            // description:<p>门店:{i.name}&ensp;所属渠道:{i.region_name}&ensp;联系人:{i.contact}&ensp;联系电话:{i.phone}&ensp;地址:{i.address}</p>
          });

          _this.setState({
            loading: false,
            data: _data,
            pagination,
          });
        }
      }
    });

    this.setState({ loading: false });
  }
  componentWillMount() {
    this.fetch({ page: 1 });
  }
  menuClick(e) {
    console.log(e.item.props.value);
    this.setState({ dropDown: e.item.props.value });
  }
  render() {
    const { data, pagination, loading, columns, visible, formLoading } = this.state;
    const { getFieldDecorator } = this.props.form;
    // const customerMemu=(
    //   <Menu onClick={this.menuClick.bind(this) } selectedKeys={[dropDown]}>
    //     <Menu.Item value='所有线索'>
    //       <a target="_blank" rel="noopener noreferrer">所有线索</a>
    //     </Menu.Item>
    //     <Menu.Item value='我的线索'>
    //       <a target="_blank" rel="noopener noreferrer" >我的线索</a>
    //     </Menu.Item>
    //     <Menu.Item value='aaaa'>
    //       <a target="_blank" rel="noopener noreferrer">aaaa</a>
    //     </Menu.Item>
    //   </Menu>
    // )
    return (
      <Layout style={{ background: '#fff', height: '100%' }}>
        <Content >
          <Row >
            <Col span={7} xl={{ span: 7 }} xs={7} style={{ padding: '24px 25px 0px' }}>
              <Breadcrumb style={{ fontSize: 14 }}>
                <Breadcrumb.Item>门店</Breadcrumb.Item>
              </Breadcrumb>
            </Col>
            <Col xl={{ span: 6, offset: 10 }} lg={{ span: 6, offset: 10 }} md={{ span: 6, offset: 10 }} sm={{ span: 6, offset: 10 }} style={{ lineHeight: '60px', textAlign: 'right' }}>
              <Button ><Link to={{ pathname: '/app/store_new', query: { current: this.props.location.query.current, uid: this.props.location.query.uid }}}>新建门店</Link></Button>
            </Col>
          </Row>
          <Layout className={`${style.tb_serbor}`} >
            <Table
              columns={columns}
              dataSource={data} onRowClick={this.handleRowClick}
              pagination={pagination}
              loading={loading}
              onChange={this.handleTableChange.bind(this)}
              style={{ marginTop: '30px' }}
            />
          </Layout>
          <Modal
            visible={visible}
            title="门店提成"
            footer={null}
          >
            <Form onSubmit={this.handleSubmit} className="login-form">
              <FormItem label="门店提成(%)">
                {getFieldDecorator('rate', {
                  rules: [{ required: true, message: '请输入提成！' }],
                })(
                  <Input type="number" placeholder="提成"/>
                )}
              </FormItem>
              <FormItem style={{ textAlign: 'right' }}>
                <Button key="back" onClick={this.handleCancel}>取消</Button>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={formLoading}
                >
                  确认
                </Button>
              </FormItem>
            </Form>
          </Modal>
        </Content>
      </Layout>
    );
  }
}

//expandedRowRender={record => <div>{record.description}</div>}
// <Input.Search
                //   placeholder="input search text"
                //   style={{ width: 200 }}
                //   onSearch={value => console.log(value)}
                //  />
// StoresList.contextTypes = {
//   router: PropTypes.object
// };
function mapStateToProps(state) {
  return { channels: state.channels };
}

const EditForm = Form.create()(StoresList);

export default connect(({ dynamic }) => ({
  dynamic,
}))(EditForm);
